package com.cxh.rmsq.ui.activity.self;

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.CheckBox
import android.widget.EditText
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.blankj.utilcode.util.ConvertUtils
import com.cxh.rmsq.R
import com.cxh.rmsq.common.Constant
import com.cxh.rmsq.common.IntentExtra
import com.cxh.rmsq.db.model.GroupEntity
import com.cxh.rmsq.im.IMManager
import com.cxh.rmsq.net.RetrofitUtil
import com.cxh.rmsq.net.newNet.ProjectViewModel
import com.cxh.rmsq.ui.activity.TitleBaseActivity
import com.cxh.rmsq.ui.activity.WebViewActivity
import com.cxh.rmsq.ui.adapter.self.CampClockImageAdapter
import com.cxh.rmsq.utils.CustomPermissionUtil
import com.cxh.rmsq.utils.GlideEngine
import com.cxh.rmsq.utils.MyUtils
import com.cxh.rmsq.utils.ToastUtils
import com.cxh.rmsq.utils.getLocalIPv4Address
import com.cxh.rmsq.utils.log.SLog
import com.cxh.rmsq.utils.recyclerview.FullyGridLayoutManager
import com.cxh.rmsq.utils.recyclerview.GridSpacingItemDecoration
import com.cxh.rmsq.viewmodel.SocialCircleViewModel
import com.cxh.rmsq.viewmodel.UserInfoViewModel
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.hjq.shape.view.ShapeTextView
import com.luck.picture.lib.basic.PictureSelectionModel
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnExternalPreviewEventListener
import com.luck.picture.lib.interfaces.OnPermissionsInterceptListener
import com.luck.picture.lib.interfaces.OnRequestPermissionListener
import com.luck.picture.lib.permissions.PermissionChecker
import com.luck.picture.lib.permissions.PermissionConfig
import com.luck.picture.lib.permissions.PermissionResultCallback
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.enums.PopupAnimation
import com.lxj.xpopup.util.XPopupUtils
import java.util.Arrays

/**
 * 发布动态
 */
class PublishCommunityActivity : TitleBaseActivity(), View.OnClickListener {
    private val et_content: EditText by lazy { findViewById<EditText>(R.id.et_content) }

    private val checkbox: CheckBox by lazy { findViewById<CheckBox>(R.id.checkbox) }
    private val checkbox1: CheckBox by lazy { findViewById<CheckBox>(R.id.checkbox1) }
    private val stv_caogao: ShapeTextView by lazy { findViewById<ShapeTextView>(R.id.stv_caogao) }
    private val stv_publish: ShapeTextView by lazy { findViewById<ShapeTextView>(R.id.stv_publish) }
    private val tv_group: TextView by lazy { findViewById<TextView>(R.id.tv_group) }
    private val tv_service: TextView by lazy { findViewById<TextView>(R.id.tv_service) }
    private val tv_visibility: TextView by lazy { findViewById<TextView>(R.id.tv_visibility) }
    private val tv_circle: TextView by lazy { findViewById<TextView>(R.id.tv_circle) }
    private val rl_visibility: RelativeLayout by lazy { findViewById<RelativeLayout>(R.id.rl_visibility) }
    private val rl_circle: RelativeLayout by lazy { findViewById<RelativeLayout>(R.id.rl_circle) }
    private val rl_group: RelativeLayout by lazy { findViewById<RelativeLayout>(R.id.rl_group) }
    private val rlvCampClockImages: RecyclerView by lazy { findViewById<RecyclerView>(R.id.rlv_camp_clock_images) }

    private val visibleList: MutableList<String> = ArrayList()
    private var auth = 2 //1:所有人可见 2：订阅者可见 3：指定好友可见 4：仅自己可以见 5：草稿
    private var circleId = ""
    private var groupId = ""
    private var content = ""
    private var files = ""
    private var Ip = ""
    private var IpLocation = ""
    private var fileType = 3 // 1:图片 2:视频  3
    private var pictureDownload = 1
    private var isDraft = 1 //1:不是草稿 2:是草稿
    private var visibleIds: MutableList<String>? = null
    private var socialCircleViewModel: SocialCircleViewModel? = null
    var typeList: MutableList<GroupEntity>? = null

    //声明mLocationClient对象
    var mLocationClient: AMapLocationClient? = null

    //声明mLocationOption对象
    var mLocationOption: AMapLocationClientOption? = null
    private val viewModel by lazy {
        ViewModelProvider.NewInstanceFactory().create(ProjectViewModel::class.java)
    }
    private var imageAdapter: CampClockImageAdapter? = null
    private val imagesMediaList = java.util.ArrayList<LocalMedia>()
    private var imageSelectMax = 9
    private var userInfoViewModel: UserInfoViewModel? = null
    private var trendId = ""//动态ID

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_publish_community)
        trendId = intent.getStringExtra("id").toString()

        if (TextUtils.isEmpty(trendId)) {
            titleBar.tvTitle.text = "发布动态"
        } else {
            titleBar.tvTitle.text = "编辑动态"
            viewModel.getDraftContent(trendId) {
                et_content.setText(it.data.content.toString())
                Ip = it.data.ip.toString()
                IpLocation = it.data.ipLocation.toString()
                fileType = it.data.fileType
                files = it.data.files.toString()
                auth = it.data.auth
                if (visibleIds != null && visibleIds!!.size > 0) {
                    visibleIds!!.addAll(it.data.visibleIds!!)
                }
                pictureDownload = it.data.pictureDownload
                when (auth) {
                    1 -> {
                        tv_visibility.text = "全部可见"
                    }

                    2 -> {
                        tv_visibility.text = "仅好友可见"
                    }

                    3 -> {
                        tv_visibility.text = "只给谁看"
                    }

                    4 -> {
                        tv_visibility.text = "仅自己可见"
                    }
                }
                checkbox.isChecked = pictureDownload != 1
                if (TextUtils.isEmpty(it.data.circleName)) {
                    tv_circle.text = "全部动态"
                    circleId = ""
                } else {
                    tv_circle.text = it.data.circleName
                    circleId = it.data.circleId.toString()
                }
                if (TextUtils.isEmpty(it.data.groupsName)) {
                    tv_group.text = "不绑定群聊"
                    groupId = ""
                } else {
                    tv_group.text = it.data.groupsName
                    groupId = it.data.groupId.toString()
                }
                if (!TextUtils.isEmpty(files)) {
                    if (files.contains(",")) {
                        for (j in 0 until MyUtils.toList(it.data.files).size) {
                            val localMedia = LocalMedia()
                            localMedia.path = MyUtils.toList(it.data.files)[j]
                            imagesMediaList.add(localMedia)
                        }
                    } else {
                        val localMedia = LocalMedia()
                        localMedia.path = it.data.files
                        imagesMediaList.add(localMedia)
                    }
                    imageAdapter!!.notifyDataSetChanged()
                }
            }
        }
        titleBar.btnLeft.setOnClickListener {
            if (!TextUtils.isEmpty(
                    et_content.text.toString().trim()
                ) || !TextUtils.isEmpty(files)
            ) {
                backTips()
            } else {
                finish()
            }
        }
        socialCircleViewModel = ViewModelProviders.of(this).get(
            SocialCircleViewModel::class.java
        )
        userInfoViewModel =
            ViewModelProviders.of(this).get<UserInfoViewModel>(UserInfoViewModel::class.java)
//        getLocationData()
//        initLocation()
        initData()

//        Ip = MyUtils.getLocalIpAddress()
        Ip = getLocalIPv4Address().toString()
        Log.e("Ip", Ip)
//        rl_visibility.setOnClickListener(this) //默认仅好友可见 暂时隐藏选择范围
        rl_circle.setOnClickListener(this)
        rl_group.setOnClickListener(this)
        checkbox.setOnClickListener(this)
        stv_caogao.setOnClickListener(this)
        stv_publish.setOnClickListener(this)
        initRegistrationTerms()
    }

    override fun onRestart() {
        super.onRestart()
//        getLocationData()
//        initLocation()
    }

    private fun initData() {
        viewModel.getCircleTypeList {
            typeList = it.data
        }


        val manager = FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false)
        rlvCampClockImages.setLayoutManager(manager)
        val itemAnimator: RecyclerView.ItemAnimator = rlvCampClockImages.getItemAnimator()!!
        if (itemAnimator != null) {
            (itemAnimator as SimpleItemAnimator).supportsChangeAnimations =
                false
        }
        rlvCampClockImages.addItemDecoration(
            GridSpacingItemDecoration(4, ConvertUtils.dp2px(5f), false)
        )
        imageAdapter = CampClockImageAdapter(this, imagesMediaList)
        rlvCampClockImages.setAdapter(imageAdapter)
        imageAdapter!!.setOnItemClickListener(object : CampClockImageAdapter.OnItemClickListener {
            override fun onItemClick(v: View?, position: Int) {
                // 预览图片、视频、音频
                PictureSelector.create(this@PublishCommunityActivity)
                    .openPreview()
                    .setImageEngine(GlideEngine.createGlideEngine())
                    .isPreviewFullScreenMode(true)
                    .isPreviewZoomEffect(true, rlvCampClockImages)
                    .setExternalPreviewEventListener(object : OnExternalPreviewEventListener {
                        override fun onPreviewDelete(position: Int) {
                            if (imagesMediaList.size > position) {
                                imagesMediaList.removeAt(position)
                                imageAdapter!!.notifyItemRemoved(position)
                            }
                            files = ""
                            if (imagesMediaList.size > 0) {
                                for (j in 0 until imagesMediaList.size) {
                                    viewModel.updateSinglePic(imagesMediaList.get(j).realPath) {
                                        runOnUiThread {
                                            if (files == "") {
                                                files = it.data
                                            } else {
                                                files = files + "," + it.data
                                            }

                                            Log.e("imgpath", files)
                                        }
                                    }

                                }
                            }
                        }

                        override fun onLongPressDownload(
                            context: Context,
                            media: LocalMedia
                        ): Boolean {
                            return true
                        }
                    })
                    .startActivityPreview(position, true, imagesMediaList)
            }

            override fun openPicture() {
                XPopup.Builder(this@PublishCommunityActivity)
                    .dismissOnTouchOutside(true)
                    .dismissOnBackPressed(true)
                    .asBottomList("", arrayOf("视频", "图片")) { pos, text ->
                        selectPicture(pos)
                    }
                    .show()
            }
        })
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.rl_visibility -> {
                visibleList.clear()
                visibleList.add("全部可见") //1 2 3 4
                visibleList.add("仅好友可见")
                visibleList.add("只给谁看")
                visibleList.add("仅自己可见")
                XPopup.Builder(this@PublishCommunityActivity)
                    .dismissOnTouchOutside(true)
                    .dismissOnBackPressed(true)
                    .asBottomList("", visibleList.toTypedArray()) { pos, text ->
                        auth = pos + 1
                        tv_visibility!!.text = text
                        if (pos == 2) {
                            //选择好友
                            startActivityForResult(
                                Intent(this, SelectSomeFriendActivity::class.java), 100
                            )
//                            val intent = Intent(this, SelectCreateGroupActivity::class.java)
//                            intent.putExtra("isCreateGroup", "1")
//                            startActivityForResult(intent, 100)
                        }
                    }
                    .show()
            }

            R.id.rl_circle -> {
                var typeName = mutableListOf<String>()
                if (typeList!!.size > 0) {
                    for (j in 0 until typeList!!.size) {
                        typeName.add(typeList!![j].name)
                    }
                    typeName.add(0, "全部")
                    XPopup.Builder(this@PublishCommunityActivity)
                        .dismissOnTouchOutside(false)
                        .dismissOnBackPressed(true)
                        .maxHeight((XPopupUtils.getAppHeight(this) as Int * .65f).toInt())
                        .asBottomList("", typeName.toTypedArray()) { pos, text ->
                            if (pos == 0) {
                                circleId = ""
                                tv_circle.text = "全部动态"
                            } else {
                                circleId = typeList!![pos - 1].id
                                tv_circle.text = text
                            }
                        }
                        .show()
                }
            }

            R.id.rl_group -> {
                startActivityForResult(
                    Intent(this, SelectOneGroupActivity::class.java), 200
                )
            }

            R.id.checkbox -> {
                if (checkbox.isChecked) {
                    pictureDownload = 0
                } else {
                    pictureDownload = 1
                }
            }

            R.id.stv_caogao -> {
                isDraft = 2
                if (MyUtils.isFastClick()) {
                    return
                }
                content = et_content.text.toString().trim()
                if (TextUtils.isEmpty(content) && TextUtils.isEmpty(files)) {
                    ToastUtils.showToast("动态内容或者图片视频不能为空")
                    return
                }
                if (content.length < 10) {
                    ToastUtils.showToast("动态内容不能少于10个字")
                    return
                }
                XPopup.Builder(this)
                    .hasNavigationBar(false)
                    .isViewMode(true)
                    .isDestroyOnDismiss(true)
                    .hasBlurBg(true) //是否设置背景为高斯模糊背景。默认为false
                    .dismissOnTouchOutside(false) //设置点击弹窗外面是否关闭弹窗，默认为true
                    .autoDismiss(false) //设置当操作完毕后是否自动关闭弹窗，默认为true。比如：点击Confirm弹窗的确认按钮默认是关闭弹窗，如果为false，则不关闭
                    .popupAnimation(PopupAnimation.NoAnimation) // 为弹窗设置内置的动画器，默认情况下，已经为每种弹窗设置了效果最佳的动画器；如果你不喜欢，仍然可以修改。
                    .asConfirm("", "确定保存到草稿箱吗？",
                        "取消", "保存",
                        {
                            val paramsMap = HashMap<String, Any>()
                            if (!TextUtils.isEmpty(trendId)) {
                                paramsMap.put("id", trendId)
                            }
                            paramsMap.put("userId", IMManager.getInstance().currentId)
                            paramsMap.put("ip", "")
                            paramsMap.put("ipLocation", "")
                            paramsMap.put("content", content)
                            paramsMap.put("fileType", fileType);
                            paramsMap.put("files", files);
                            paramsMap.put("circleId", circleId);//
                            paramsMap.put("auth", auth);
                            if (visibleIds != null && visibleIds!!.size > 0) {
                                paramsMap.put("visibleIds", visibleIds!!);
                            }
                            paramsMap.put("groupId", groupId);
                            paramsMap.put("pictureDownload", pictureDownload);
                            paramsMap.put("isDraft", isDraft);
                            val body = RetrofitUtil.createJsonRequest(paramsMap)
                            if (TextUtils.isEmpty(trendId)) {
                                socialCircleViewModel!!.createCommunity(body)
                                socialCircleViewModel!!.createCommunity().observe(this) { result ->
                                    if (result.code == 200) {
                                        ToastUtils.showToast("存草稿箱成功")
                                        finish()
                                    } else {
                                        ToastUtils.showToast(result.msg)
                                    }
                                }
                            } else {
                                viewModel.draftEditing(paramsMap) {
                                    if (it.code == 200) {
                                        ToastUtils.showToast("存草稿箱成功")
                                        finish()
                                    } else {
                                        ToastUtils.showToast(it.msg)
                                    }
                                }
                            }

                        }, {

                        }, false/*, R.layout.custom_confirm_pop*/
                    ).show()


                /*var bean = SaveDataBeans()
                bean.userId = IMManager.getInstance().currentId
                bean.ip = Ip
                bean.ipLocation = IpLocation
                bean.content = content
                bean.fileType = fileType
                bean.files = files
                bean.circleId = circleId
                bean.auth = auth
                bean.groupId = groupId
                bean.pictureDownload = pictureDownload
                bean.isDraft = isDraft
                if (visibleIds != null && visibleIds!!.size > 0) {
                    bean.visibleIds = visibleIds
                }
                viewModel.draftToPublish(bean) {
                    if (it.code == 200) {
                        ToastUtils.showToast("存草稿箱成功")
                        finish()
                    } else {
                        ToastUtils.showToast(it.msg)
                    }
                }*/
            }

            R.id.stv_publish -> {
                if (imagesMediaList.size == 0) {
                    fileType = 3
                    files = ""
                }
                isDraft = 1
                if (MyUtils.isFastClick()) {
                    return
                }
                content = et_content.text.toString().trim()
                if (TextUtils.isEmpty(content) && TextUtils.isEmpty(files)) {
                    ToastUtils.showToast("动态内容或者图片视频不能为空")
                    return
                }
                if (content.length < 10) {
                    ToastUtils.showToast("动态内容不能少于10个字")
                    return
                }
                if (!checkbox1.isChecked) {
                    showToast("请阅读并同意人脉社区用户行为规范")
                    return
                }
                val paramsMap = HashMap<String, Any>()
                if (!TextUtils.isEmpty(trendId)) {
                    paramsMap.put("id", trendId)
                }
                paramsMap.put("userId", IMManager.getInstance().currentId)
                paramsMap.put("ip", "")
                paramsMap.put("ipLocation", "")
                paramsMap.put("content", content)
                paramsMap.put("fileType", fileType);
                paramsMap.put("files", files);
                paramsMap.put("circleId", circleId);//
                paramsMap.put("auth", auth);
                if (visibleIds != null && visibleIds!!.size > 0) {
                    paramsMap.put("visibleIds", visibleIds!!);
                }
                paramsMap.put("groupId", groupId);
                paramsMap.put("pictureDownload", pictureDownload);
                paramsMap.put("isDraft", isDraft);
                val body = RetrofitUtil.createJsonRequest(paramsMap)
                if (TextUtils.isEmpty(trendId)) {
                    socialCircleViewModel!!.createCommunity(body)
                    socialCircleViewModel!!.createCommunity()
                        .observe(
                            this
                        ) { result ->
                            if (result.code == 200) {
                                ToastUtils.showToast("内容审核通过，发布成功！")
                                finish()
                            } else {
                                ToastUtils.showToast(result.msg)
                            }
                        }
                } else {
                    viewModel.draftToPublish(paramsMap) {
                        if (it.code == 200) {
                            ToastUtils.showToast("内容审核通过，发布成功！")
                            finish()
                        } else {
                            ToastUtils.showToast(it.msg)
                        }
                    }
                }

            }
        }
    }


    private fun initRegistrationTerms() {
        //协议文字及点击事件设置
        val serviceStr = tv_service.text.toString().trim { it <= ' ' }
        val stringBuilder = SpannableStringBuilder(serviceStr)
        val clickableSpanOne: ClickableSpan = object : ClickableSpan() {
            override fun onClick(view: View) {
                val intent = Intent(
                    this@PublishCommunityActivity,
                    WebViewActivity::class.java
                )
                intent.putExtra(WebViewActivity.PARAMS_TITLE, "行为规范")
                intent.putExtra(WebViewActivity.PARAMS_URL, Constant.behaviorStandard)
                startActivity(intent)
            }

            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.color = Color.parseColor("#333333")
                // 设置下划线 true显示、false不显示
                //paint.setTypeface(Typeface.DEFAULT_BOLD);
                ds.isUnderlineText = false
            }
        }

        stringBuilder.setSpan(clickableSpanOne, 7, 19, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        // 不设置点击不生效
        tv_service.text = stringBuilder
        tv_service.movementMethod = LinkMovementMethod.getInstance() // 不设置 没有点击事件
        tv_service.highlightColor = Color.TRANSPARENT // 设置点击后的颜色为透明
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                100 -> {
                    val memberList = data!!.getStringArrayListExtra(IntentExtra.LIST_STR_ID_LIST)
                    visibleIds!!.addAll(memberList!!)
                    SLog.i("PublishCommunityActivity", "memberList.size = " + memberList.size)
                }

                200 -> {
                    groupId = data!!.getStringExtra(IntentExtra.LIST_STR_ID_LIST).toString()
                    val groupName = data!!.getStringExtra("groupName")
                    tv_group.text = groupName
                    SLog.i("PublishCommunityActivity", "===== $groupId-$groupName")
                }

                PictureConfig.CHOOSE_REQUEST -> {
                    val selectList =
                        PictureSelector.obtainSelectorList(data)
                    val isMaxSize = selectList.size == imageSelectMax
                    val oldSize = imagesMediaList.size
                    imageAdapter!!.notifyItemRangeRemoved(
                        0,
                        if (isMaxSize) oldSize + 1 else oldSize
                    )

                    imagesMediaList.clear()
                    imagesMediaList.addAll(selectList)
                    imageAdapter!!.notifyItemRangeInserted(0, selectList.size)

//                    for (media in result) {
                    files = ""
                    showLoadingDialog("上传中")
                    for (j in 0 until imagesMediaList.size) {
                        viewModel.updateSinglePic(imagesMediaList.get(j).realPath) {
                            runOnUiThread {
                                if (files == "") {
                                    files = it.data
                                } else {
                                    files = files + "," + it.data
                                }

                                Log.e("imgpath", files)
                                dismissLoadingDialog()
                            }
                        }
                    }
                }

                else -> {}
            }
        }
    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!TextUtils.isEmpty(
                    et_content.text.toString().trim()
                ) || !TextUtils.isEmpty(files)
            ) {
                backTips()
            } else {
                finish()
            }
            false
        } else {
            super.onKeyDown(keyCode, event)
        }
    }

    var popupView: BasePopupView? = null

    private fun backTips() {
        popupView = XPopup.Builder(this)
            .hasNavigationBar(false)
            .isViewMode(true)
            .isDestroyOnDismiss(true)
            .hasBlurBg(true) //是否设置背景为高斯模糊背景。默认为false
            .dismissOnTouchOutside(false) //设置点击弹窗外面是否关闭弹窗，默认为true
            .autoDismiss(false) //设置当操作完毕后是否自动关闭弹窗，默认为true。比如：点击Confirm弹窗的确认按钮默认是关闭弹窗，如果为false，则不关闭
            .popupAnimation(PopupAnimation.NoAnimation) // 为弹窗设置内置的动画器，默认情况下，已经为每种弹窗设置了效果最佳的动画器；如果你不喜欢，仍然可以修改。
            .asConfirm("", "已经编辑好确定要退出吗？",
                "确定", "取消",
                {
                    popupView?.dismiss()
                }, {
                    finish()
                    popupView?.dismiss()
                }, false/*, R.layout.custom_confirm_pop*/
            ).show()
    }

    private fun selectPicture(type: Int) {
        val pictureSelector = PictureSelector.create(this)
        //        PictureSelector.create(this)
        var pictureSelectionModel: PictureSelectionModel? = null
        if (type == 1) {
            imageSelectMax = 9
            fileType = 1
            pictureSelectionModel = pictureSelector.openGallery(SelectMimeType.ofImage())
        } else if (type == 0) {//视频
            pictureSelectionModel = pictureSelector.openGallery(SelectMimeType.ofVideo())
            imageSelectMax = 1
            fileType = 2
        }

        pictureSelectionModel!!.setImageEngine(GlideEngine.createGlideEngine())
            .setMaxSelectNum(imageSelectMax)
            .isGif(true)
            .isMaxSelectEnabledMask(true)
            .isOriginalControl(true)
            .setSelectedData(imagesMediaList)
            .setPermissionsInterceptListener(object : OnPermissionsInterceptListener {
                override fun requestPermission(
                    fragment: Fragment,
                    permissionArray: Array<String>,
                    call: OnRequestPermissionListener
                ) {
                    val permissionInfoDialog = Dialog(fragment.requireActivity())
                    //应用上架要求添加权限使用说明
                    var permissionInfoTitle = ""
                    var permissionInfoContent = ""
                    if (Arrays.equals(
                            permissionArray,
                            PermissionConfig.getReadPermissionArray(
                                fragment.context,
                                SelectMimeType.ofImage()
                            )
                        )
                    ) {
                        permissionInfoTitle =
                            resources.getString(R.string.permission_info_title_storage)
                        permissionInfoContent =
                            resources.getString(R.string.permission_info_content_storage)
                    } else if (Arrays.equals(permissionArray, PermissionConfig.CAMERA)) {
                        permissionInfoTitle =
                            resources.getString(R.string.permission_info_title_camera)
                        permissionInfoContent =
                            resources.getString(R.string.permission_info_content_camera)
                    }
                    if (!TextUtils.isEmpty(permissionInfoTitle) && !TextUtils.isEmpty(
                            permissionInfoContent
                        )
                    ) {
                        CustomPermissionUtil.showPermissionInfo(
                            fragment.activity,
                            permissionInfoDialog,
                            permissionInfoTitle,
                            permissionInfoContent
                        )
                    }

                    //此处使用图片选择框架的权限申请
                    PermissionChecker.getInstance().requestPermissions(
                        fragment,
                        permissionArray,
                        object : PermissionResultCallback {
                            override fun onGranted() {
                                permissionInfoDialog.dismiss()
                                call.onCall(permissionArray, true)
                            }

                            override fun onDenied() {
                                permissionInfoDialog.dismiss()
                                call.onCall(permissionArray, false)
                            }
                        })
                }

                override fun hasPermissions(
                    fragment: Fragment,
                    permissionArray: Array<String>
                ): Boolean {
                    return PermissionChecker.isCheckSelfPermission(
                        fragment.context,
                        permissionArray
                    )
                }
            })
            .setPermissionDeniedListener { fragment, permissionArray, requestCode, call -> //权限拒绝，弹出去设置弹窗，点击设置跳转到应用权限系统设置页面
                var permissionSetContent = ""
                if (Arrays.equals(
                        permissionArray,
                        PermissionConfig.getReadPermissionArray(
                            fragment.context,
                            SelectMimeType.ofImage()
                        )
                    )
                ) {
                    permissionSetContent = resources.getString(R.string.permission_set_storage)
                } else if (Arrays.equals(permissionArray, PermissionConfig.CAMERA)) {
                    permissionSetContent = resources.getString(R.string.permission_set_camera)
                }
                if (!TextUtils.isEmpty(permissionSetContent)) {
                    CustomPermissionUtil.showPermissionSet(
                        fragment.activity,
                        permissionSetContent,
                        ArrayList(Arrays.asList(*permissionArray))
                    ) { call.onCall(true) }
                }
            }
            .forResult(PictureConfig.CHOOSE_REQUEST)
        /* .forResult(object : OnResultCallbackListener<LocalMedia> {
             override fun onResult(result: ArrayList<LocalMedia>) {
                 val isMaxSize = result.size == imageSelectMax
                 val oldSize = imagesMediaList.size
                 imageAdapter!!.notifyItemRangeRemoved(
                     0,
                     if (isMaxSize) oldSize + 1 else oldSize
                 )

                 imagesMediaList.clear()
                 imagesMediaList.addAll(result)
                 imageAdapter!!.notifyItemRangeInserted(0, result.size)

//                    for (media in result) {
                 files = ""
                 for (j in 0 until imagesMediaList.size) {
                     viewModel.updateSinglePic(imagesMediaList.get(j).realPath) {
                         if (files == "") {
                             files = it.data
                         } else {
                             files = files + "," + it.data
                         }

                         Log.e("imgpath", files)
                     }
//                        userInfoViewModel!!.uploadImg(imagesMediaList.get(j).realPath.toString())
//                        userInfoViewModel!!.upload()
//                            .observe(this@PublishCommunityActivity) { resource: Resource2<String?> ->
//                                if (resource.status == Status.SUCCESS && resource.data != null) {
//                                    if (files == "") {
//                                        files = resource.data.toString()
//                                    } else {
//                                        files = files + "," + resource.data
//                                    }
//
//                                    Log.e("imgpath", files)
//                                }
//                            }
                 }
             }

             override fun onCancel() {}
         })*/
    }


    private fun initLocation() {
        //初始化AMapLocationClientOption对象
        mLocationOption = AMapLocationClientOption()
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption!!.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption!!.isOnceLocation = true
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption!!.isOnceLocationLatest = true
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption!!.isNeedAddress = true
        //设置是否允许模拟位置,默认为true，允许模拟位置
        mLocationOption!!.isMockEnable = true
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
        mLocationOption!!.interval = 1000
        //设置定位请求超时时间，单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption!!.httpTimeOut = 20000
        //关闭缓存机制
        mLocationOption!!.isLocationCacheEnable = false
        try {
            mLocationClient = AMapLocationClient(this)
            //给定位客户端对象设置定位参数
            mLocationClient!!.setLocationOption(mLocationOption)
            mLocationClient!!.setLocationListener { aMapLocation ->
                //获取定位结果
                if (aMapLocation != null) {
                    if (aMapLocation.errorCode == 0) {
                        //可在其中解析amapLocation获取相应内容。
                        if (!TextUtils.isEmpty(aMapLocation.city)) {
                            IpLocation =
                                    /*aMapLocation.getCity() + "" + aMapLocation.getDistrict() + "" +*/
                                aMapLocation.address
//                            lng = aMapLocation.longitude.toString()
//                            lat = aMapLocation.latitude.toString()
//                            binding.tvMinePos.setText(address)

                            Log.e("IpLocation", IpLocation)
                        } else {
                            ToastUtils.showToast("未获取到城市名称，请重试")
                        }

                    } else {
                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        if (aMapLocation.errorCode == 12) {
                            ToastUtils.showToast("定位失败:" + "请在设置中打开定位服务开关后重试")
                        } else {
                            ToastUtils.showToast("定位失败:" + aMapLocation.errorInfo)
                        }
                    }
                }
            }
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
    }

    //获取定位权限
    private fun getLocationData() {
        //应用上架要求添加权限使用说明
        val permissionInfoDialog = Dialog(this)
        CustomPermissionUtil.showPermissionInfo(
            this, permissionInfoDialog,
            resources.getString(R.string.permission_info_title_location_camp_clock),
            resources.getString(R.string.permission_info_content_location_camp_clock)
        )

        //获取定位权限并进行定位
        XXPermissions.with(this)
            .permission(Permission.ACCESS_COARSE_LOCATION)
            .permission(Permission.ACCESS_FINE_LOCATION)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: List<String>, allGranted: Boolean) {
                    if (allGranted) {
                        permissionInfoDialog.dismiss()

                        //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
                        mLocationClient!!.stopLocation()
                        mLocationClient!!.startLocation()
                    }
                }

                override fun onDenied(permissions: List<String>, doNotAskAgain: Boolean) {
                    permissionInfoDialog.dismiss()

                    //权限拒绝，弹出去设置弹窗，点击设置跳转到应用权限系统设置页面
//                    CustomPermissionUtil.showPermissionSet(
//                        this@PublishCommunityActivity,
//                        resources.getString(R.string.permission_set_location_camp_clock),
//                        permissions
//                    ) { //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
//                        mLocationClient!!.stopLocation()
//                        mLocationClient!!.startLocation()
//                    }
                }
            })
    }

    override fun onDestroy() {
        super.onDestroy()
//        mLocationClient!!.stopLocation() //停止定位后，本地定位服务并不会被销毁
//        mLocationClient!!.onDestroy() //销毁定位客户端，同时销毁本地定位服务。
    }
}